package com.dev.drawweb.model.service;

import com.dev.drawweb.model.mapper.DrawMapper;
import com.dev.drawweb.model.pojo.Draw;
import com.dev.drawweb.model.pojo.Student;
import com.dev.drawweb.utils.DrawCacheUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.springframework.ui.Model;

import javax.mail.internet.MimeMessage;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.*;

@Service
public class DrawService {

    @Autowired
    DrawMapper drawMapper;

    @Autowired
    JavaMailSenderImpl mailSender;

    public static final String drawResPath="D:\\personal_file\\drawRes\\";

    public static final String drawDescrib="答辩结果";

    public List<Map> getDrawsByStuID(int id){return drawMapper.getDrawsByStuID(id);}

    public List<Draw> getDrawsByUserID(int id) {
        return drawMapper.getDrawsByUserID(id);
    }

    public List<Student> getStudentsResByDrawName(String drawName) { return drawMapper.getStudentsResByDrawName(drawName); }

    public int reDrawByDrawName(String drawName) {
        return drawMapper.reDrawByDrawName(drawName);
    }

    public int addDraw(int userId,String defenseName) { return drawMapper.addDraw(new Draw(userId,defenseName)); }

    public int addStudentToDraw(String drawName,int stuId) { return drawMapper.addStudentToDraw(new Draw(drawName,stuId)); }

    public int delFormDraw(int stuId,String drawName){ return drawMapper.delFromDraw(new Draw(drawName,stuId));}

    public int delFromUser(int userId,String drawName){return drawMapper.delFromUser(new Draw(userId,drawName));}

    public int upDateStuScore(String drawName,int stuId,int newScore){
        Map<String,Object> map=new HashMap<>();
        map.put("drawname",drawName);
        map.put("stuid",stuId);
        map.put("score",newScore);
        return drawMapper.upDateStuScore(map);
    }


    public void doStuDraw(String drawname,int stuid){
        List<Integer> selectArr= DrawCacheUtil.getSelectArr(drawname);
        if(selectArr==null||selectArr.isEmpty()) {//防止抽签过程中插入学生
            selectArr=new ArrayList<>();
            List<Student> students = getStudentsResByDrawName(drawname);
            boolean[] drawedMark = new boolean[students.size() + 1];
            for (Student student : students) {
                int tmpDrawRes = student.getDrawres();
                if (tmpDrawRes != -1) {
                    drawedMark[tmpDrawRes] = true;
                }
            }
            for (int i = 1; i < drawedMark.length; i++) {
                if (!drawedMark[i]) {
                    selectArr.add(i);
                }
            }
        }
        Integer drawRes=selectArr.get((int)(System.currentTimeMillis()%selectArr.size()));
        selectArr.remove(drawRes);
        DrawCacheUtil.setSelectArr(drawname,selectArr);
        Map<String,Object> map=new HashMap<>();
        map.put("drawname",drawname);
        map.put("stuid",stuid);
        map.put("drawres",drawRes);
        drawMapper.doStuDraw(map);
    }

    public List<Student> defenseOrderService(String drawName, int mod){
        List<Student> students=null;
        if(mod==0||mod==3) {
            if(mod==3){this.reDrawByDrawName(drawName);}
            students = this.getStudentsResByDrawName(drawName);
        }
        else if(mod==1){
            List<Student> allStu = this.getStudentsResByDrawName(drawName);
            students=new ArrayList<>();
            for (Student tmpStu:allStu) {
                if(tmpStu.getDrawres()!=-1){ students.add(tmpStu);}
            }
        }
        else if(mod==2){
            List<Student> allStu = this.getStudentsResByDrawName(drawName);
            students=new ArrayList<>();
            for (Student tmpStu:allStu) {
                if(tmpStu.getDrawres()==-1){ students.add(tmpStu);}
            }
        }
        return students;
    }

    public void writeDrawFile(String drawName) throws Exception {
        List<Student> allStu = this.getStudentsResByDrawName(drawName);
        StringBuilder drawRes=new StringBuilder();
        drawRes.append("学号,姓名,专业,答辩序号,答辩成绩\n");
        for (Student student:allStu) {
            drawRes.append(student.toString());
        }
        BufferedWriter out = new BufferedWriter(new FileWriter(drawResPath+drawName+drawDescrib+".csv"));
        out.write(drawRes.toString());
        out.close();
    }

    public void doDownLoadFile(String fileName, HttpServletResponse response) throws Exception {
        File file = new File(DrawService.drawResPath+fileName);
        response.setHeader("content-disposition","attachment;filename=" + URLEncoder.encode(fileName,"UTF-8"));
        response.setContentType("content-type:octet-stream");
        BufferedInputStream inputStream = new BufferedInputStream(new FileInputStream(file));
        OutputStream outputStream = response.getOutputStream();
        byte[] buffer = new byte[1024];
        int len = 0 ;
        while ((len = inputStream.read(buffer)) != -1){
            outputStream.write(buffer ,0 , len);
        }
        inputStream.close();
        outputStream.close();
    }

    public void doSendEmailFile(String drawName,String toEmail) throws Exception{
        String fileName=drawName+DrawService.drawDescrib+".csv";
        MimeMessage mimeMessage = mailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);

        helper.setSubject(drawName+"答辩结果");
        helper.setText("您的答辩结果");

        //发送附件
        helper.addAttachment(fileName,new File(DrawService.drawResPath+fileName));

        helper.setTo(toEmail);
        helper.setFrom("1391725470@qq.com");

        mailSender.send(mimeMessage);
    }

    public Integer getDrawByIdAndName(int userId,String drawName){
        return drawMapper.getDrawByIdAndName(new Draw(userId,drawName));
    }
}
